const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

const userSchema = new mongoose.Schema(
  {
    username: {
      type: String,
      required: [true, '用户名是必填项'],
      unique: true,
      trim: true,
      minlength: [3, '用户名至少需要3个字符'],
      maxlength: [20, '用户名不能超过20个字符'],
    },
    email: {
      type: String,
      required: [true, '邮箱是必填项'],
      unique: true,
      trim: true,
      lowercase: true,
      match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, '请提供有效的邮箱地址'],
    },
    password: {
      type: String,
      required: [true, '密码是必填项'],
      minlength: [6, '密码至少需要6个字符'],
      select: false, // 查询时默认不返回密码
    },
    role: {
      type: String,
      enum: ['student', 'teacher', 'parent', 'admin'],
      default: 'student',
    },
    avatar: {
      type: String,
      default: 'default-avatar.png',
    },
    age: {
      type: Number,
      min: [3, '年龄必须大于或等于3岁'],
      max: [18, '年龄必须小于或等于18岁'],
    },
    bio: {
      type: String,
      maxlength: [200, '个人简介不能超过200个字符'],
    },
    learningProgress: {
      level: {
        type: Number,
        default: 1,
      },
      experience: {
        type: Number,
        default: 0,
      },
      completedProjects: [
        {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Project',
        },
      ],
      completedChallenges: [
        {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Challenge',
        },
      ],
      badges: [
        {
          name: String,
          description: String,
          dateEarned: Date,
        },
      ],
    },
    preferences: {
      theme: {
        type: String,
        enum: ['light', 'dark', 'colorful'],
        default: 'light',
      },
      notifications: {
        email: {
          type: Boolean,
          default: true,
        },
        app: {
          type: Boolean,
          default: true,
        },
      },
    },
    isActive: {
      type: Boolean,
      default: true,
    },
    lastLogin: Date,
  },
  {
    timestamps: true, // 自动添加createdAt和updatedAt字段
  }
);

// 保存前对密码进行哈希处理
userSchema.pre('save', async function (next) {
  // 只有在密码被修改时才重新哈希
  if (!this.isModified('password')) return next();

  try {
    // 生成盐值
    const salt = await bcrypt.genSalt(10);
    // 哈希密码
    this.password = await bcrypt.hash(this.password, salt);
    next();
  } catch (error) {
    next(error);
  }
});

// 比较密码是否匹配
userSchema.methods.comparePassword = async function (candidatePassword) {
  try {
    return await bcrypt.compare(candidatePassword, this.password);
  } catch (error) {
    throw new Error(error);
  }
};

const User = mongoose.model('User', userSchema);

module.exports = User;